package myky.com.doctorapp.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gyf.barlibrary.ImmersionBar;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import myky.com.doctorapp.R;
import myky.com.doctorapp.api.Address;
import myky.com.doctorapp.base.BaseActivity;
import myky.com.doctorapp.contract.PersonInfoContract;
import myky.com.doctorapp.entity.UpUserInfoEvent;
import myky.com.doctorapp.entity.UserEntity;
import myky.com.doctorapp.presenter.PersonInfoPresenter;
import myky.com.doctorapp.utils.Constants;
import myky.com.doctorapp.utils.FileUtils;
import myky.com.doctorapp.utils.ShareUtil;
import myky.com.doctorapp.utils.ToastUtils;
import myky.com.doctorapp.wight.SelfDialog;

public class PersonalInfo2Activity extends BaseActivity<PersonInfoPresenter, UserEntity.PayLoadBean> implements PersonInfoContract.View, View.OnClickListener, InvokeListener, TakePhoto.TakeResultListener {

    @BindView(R.id.header)
    SimpleDraweeView header;
    @BindView(R.id.person_tv)
    TextView personTv;
    @BindView(R.id.conmonTitleTextView)
    TextView conmonTitleTextView;
    @BindView(R.id.backLayout)
    LinearLayout backLayout;
    @BindView(R.id.commonTitleLayout)
    LinearLayout commonTitleLayout;
    @BindView(R.id.person_username)
    TextView personUsername;
    @BindView(R.id.activity_personal_data_re)
    RelativeLayout activityPersonalDataRe;
    @BindView(R.id.person_tv1)
    TextView personTv1;
    @BindView(R.id.activity_personal_data_re1)
    RelativeLayout activityPersonalDataRe1;
    @BindView(R.id.person_tv2)
    TextView personTv2;
    @BindView(R.id.activity_personal_data_re2)
    RelativeLayout activityPersonalDataRe2;
    @BindView(R.id.person_tv3)
    TextView personTv3;
    @BindView(R.id.activity_personal_data_re3)
    RelativeLayout activityPersonalDataRe3;
    @BindView(R.id.person_tv4)
    TextView personTv4;
    @BindView(R.id.activity_personal_data_re4)
    RelativeLayout activityPersonalDataRe4;
    @BindView(R.id.person_tv5)
    TextView personTv5;
    @BindView(R.id.activity_personal_data_re5)
    RelativeLayout activityPersonalDataRe5;
    @BindView(R.id.activity_personal_data)
    LinearLayout activityPersonalData;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private static int output_X = 200;
    private static int output_Y = 200;
    private SelfDialog selfDialog;
    private Uri outPutUri;


    @Override
    protected void reloadActivity() {

    }

    @Override
    protected View injectTarget() {
        return findViewById(R.id.injectView);
    }

    @Override
    protected void initData() {
        mPresenter.getUserInfo();
    }

    @Override
    protected void initView() {


        takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));

        conmonTitleTextView.setText("个人信息");

        ImmersionBar.with(this).barColorInt(ContextCompat.getColor(this, R.color.colorPrimary)).titleBar(R.id.commonTitleLayout).navigationBarEnable(false).init();

    }

    @Override
    public int getContenView() {
        return R.layout.activity_personal_info;
    }

    @Override
    public PersonInfoPresenter getPresenter() {
        return new PersonInfoPresenter();
    }

    @Override
    public void showDataSuccess(UserEntity.PayLoadBean datas) {


        personUsername.setText(datas.getRealname());


        personTv3.setText(datas.getConcatTelephone());


        header.setImageURI(Address.IMAGE + datas.getHeadPhoto());

        personTv.setText(datas.getNickname());

    }

    @Override
    public void onClick(View view) {

    }


    @Override
    public void takeSuccess(TResult result) {

       String path=result.getImage().getOriginalPath();

       if(com.blankj.utilcode.util.FileUtils.isFileExists(path)){

       mPresenter.upLoadPic(new File(path));

       }


    }

    @Override
    public void takeFail(TResult result, String msg) {

        ToastUtils.show(msg);

    }

    @Override
    public void takeCancel() {

    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType types = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());

        if (PermissionManager.TPermissionType.WAIT.equals(types)) {
            this.invokeParam = invokeParam;
        }
        return types;
    }


    @Override
    public void updateInfoFailed() {

    }

    @Override
    public void showUpdateResult(String userName, String advanter) {
        if (userName != null) {

            ShareUtil.putData(Constants.USERNAME, userName);


            personTv.setText(userName);


            EventBus.getDefault().post(new UpUserInfoEvent(userName, advanter));


        }
    }

    @Override
    public void showUpSuccesMd5(String md5Url) {



        header.setImageURI(Address.IMAGE+md5Url);

        EventBus.getDefault().post(new UpUserInfoEvent(null, md5Url));


        mPresenter.updateUserInfo(null,md5Url,"v1.0");


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePhoto.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        takePhoto.onSaveInstanceState(outState);
    }


    @OnClick({R.id.backLayout, R.id.header,R.id.activity_personal_data_re})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backLayout:
                finish();
                break;
            case R.id.header:


                final CropOptions options=new CropOptions.Builder()
                        .setOutputX(output_X)
                        .setOutputY(output_Y)
                        .setWithOwnCrop(false)
                        .setAspectY(1)
                        .setAspectX(1)
                        .create();

                selfDialog = new SelfDialog(PersonalInfo2Activity.this);
                selfDialog.setTitle("选择图片来源");
                selfDialog.setYesOnclickListener("从相机拍照", new SelfDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        try {
                            outPutUri = Uri.fromFile(FileUtils.createHeadPhotoSDDir());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        takePhoto.onPickFromCaptureWithCrop(outPutUri,options);
                        selfDialog.dismiss();
                    }
                });
                selfDialog.setNoOnclickListener("从相册获取", new SelfDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        try {
                            outPutUri = Uri.fromFile(FileUtils.createHeadPhotoSDDir());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        takePhoto.onPickFromGalleryWithCrop(outPutUri,options);
                        selfDialog.dismiss();
                    }
                });


                selfDialog.show();


                break;

            case R.id.activity_personal_data_re:
                uploadType = "realname";
                setTextViews(findViewById(R.id.person_tv), "更新昵称", personTv.getText().toString(), "请输入昵称", 1);
                break;
        }
    }
    private String uploadType;

    //输入类型对话框
    public void setTextViews(final TextView textView, String title, String editText, String hintText, final int i){


        selfDialog=new SelfDialog(this,uploadType,true,"EditText",false);
        selfDialog.setTitle(title);
        selfDialog.setEditText(editText,null,hintText);
        selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesBackOnclickListener() {
            @Override
            public void onYesClick(final List<String> strings) {


                if (strings!=null&&strings.size()>0&&!strings.get(0).equals(" ")) {
                    Log.i("out", "strings" + strings);
                    if (uploadType.equals("realname")) {


                        String realname = strings.get(0);

                        if (realname.length() < 13 && realname.length() > 1) {

                            KeyboardUtils.toggleSoftInput();

                            mPresenter.updateUserInfo(realname, null, "v1.0");


                        } else {
                            ToastUtils.show("请输入2-12字的昵称");
                        }
                    }
                }

                selfDialog.dismiss();
            }
        });

        selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                selfDialog.dismiss();
            }
        });

        selfDialog.show();
    }
}
